//
//  SignInSuccessView.m
//  SameCityDriver
//
//  Created by mac on 2020/3/24.
//  Copyright © 2020 GCY. All rights reserved.
//

#import "WithdrawalConfirmView.h"

@interface WithdrawalConfirmView()

@property (nonatomic, strong) UITextField *phoneTextField;
@property (nonatomic, strong) UITextField *codeTextField;
@property (nonatomic, copy)   NSString *imgUrl;

@end

@implementation WithdrawalConfirmView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setUpUI];
    }
    
    return self;
}

- (void)setUpUI {
    
    //确认信息底层白色View
    
    
    //    UIImageView *tipImage = [[UIImageView alloc] initWithFrame:CGRectMake((ScreenW-100)/2-25, 40, 50, 50)];
    //    tipImage.image = image(@"gcy_img_alert_lingdang");
    //    [confirView addSubview:tipImage];
    
    _phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 30, self.width - 120, 40)];
    _phoneTextField.font = font(14);
    _phoneTextField.text = @"";
    _phoneTextField.backgroundColor = [UIColor whiteColor];
    _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请填写手机号" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    _phoneTextField.textColor = Dark_TextColor;
    _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phoneTextField.enabled = NO;
    [DCSpeedy dc_chageControlCircularWith:_phoneTextField AndSetCornerRadius:3 SetBorderWidth:1 SetBorderColor:BackgroundColor canMasksToBounds:YES];
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 40)];
    _phoneTextField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
    _phoneTextField.leftViewMode = UITextFieldViewModeAlways;
    [_phoneTextField addSubview: leftView];
    [self addSubview:_phoneTextField];
    
    _codeTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, _phoneTextField.bottom + 10, self.width - 120, 40)];
    _codeTextField.font = font(14);
    _codeTextField.text = @"";
    _codeTextField.backgroundColor = [UIColor whiteColor];
    _codeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _codeTextField.keyboardType = UIKeyboardTypeNumberPad;
    _codeTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请填写验证码" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    _codeTextField.textColor = Dark_TextColor;
    _codeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [DCSpeedy dc_chageControlCircularWith:_codeTextField AndSetCornerRadius:3 SetBorderWidth:1 SetBorderColor:BackgroundColor canMasksToBounds:YES];
    UIView *leftView2= [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 40)];
    _codeTextField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
    _codeTextField.leftViewMode = UITextFieldViewModeAlways;
    [_codeTextField addSubview: leftView2];
    [self addSubview:_codeTextField];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    cut(button, 3);
    button.tag = 50;
    button.frame = CGRectMake(self.width - 15 - 80, _phoneTextField.top + 5, 80, 30);
    button.titleLabel.font = [UIFont systemFontOfSize:13];
    button.backgroundColor = Theme_ColorValue;
    [button setTitle:@"验证码" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btnTypeClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];
    
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cut(confirmButton, BTN_BORDER_RADIUS);
    confirmButton.tag = 51;
    confirmButton.frame = CGRectMake(15, self.bottom - 15 - 40, self.width - 30, 40);
    confirmButton.titleLabel.font = [UIFont systemFontOfSize:15];
    confirmButton.backgroundColor = Theme_ColorValue;
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(btnTypeClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:confirmButton];
}

- (void)setPhoneNum:(NSString *)phoneNum {
    _phoneNum = phoneNum;
    _phoneTextField.text = phoneNum;
}

- (void)btnTypeClick:(UIButton *)button {
    @weakify(self);
    if (button.tag == 50) {
        
        NSDictionary *parmas = @{
            @"code" : _code,
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        };
        [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], MYBANKWITHDRAW_WITHDRAWAPPLY) withParameter:parmas withVC:[self findCurrentShowingViewController] netName:@"发送验证码" success:^(id response, NSString *msg) {
            
            @strongify(self);
            
            [XSInfoView showInfo:msg onView:self.window];
            
            [self theCountdown];
            
        } failure:^(NSInteger code, NSString *msg) {
           
            [XSInfoView showInfo:msg onView:self.window];
        }];
        
    } else {
        
        //确认
        if ([DCSpeedy isBlankString:_codeTextField.text] == YES) {
            [XSInfoView showInfo:@"请填写验证码" onView:self];
            return;
        }
        NSDictionary *parmas = @{
            @"smsCode" : _codeTextField.text,
            @"code" : _code,
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        };
        [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], MYBANKWITHDRAW_WITHDRAWCONFIRM) withParameter:parmas withVC:[self findCurrentShowingViewController] netName:@"确认提现" success:^(id response, NSString *msg) {
            
            @strongify(self);
            
            [XSInfoView showInfo:msg onView:self.window];

            if (self.block) {
                self.block(YES);
            }
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    }
    
}

- (void)theCountdown{
    
    UIButton *button = [self viewWithTag:50];
    
    __block int timeout= 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [button setTitle:@"验证码" forState:UIControlStateNormal];
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                //                [button setBackgroundColor:[UIColor cy_colorWithHexString:@"#FE3905"]];
                button.userInteractionEnabled = YES;
            });
            
        }else{
            
            //            int minutes = timeout / 60;
            
            int seconds = timeout % 60;
            
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [UIView beginAnimations:nil context:nil];
                
                [UIView setAnimationDuration:0];
                
                [button setTitle:[NSString stringWithFormat:@"%@ S",strTime] forState:UIControlStateNormal];
                
                [UIView commitAnimations];
                
                button.userInteractionEnabled = NO;
                
            });
            
            timeout--;
            
        }
        
    });
    
    dispatch_resume(_timer);
}


- (UIViewController *)findCurrentShowingViewController {
    //获得当前活动窗口的根视图
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentShowingVC = [self findCurrentShowingViewControllerFrom:vc];
    return currentShowingVC;
}

//注意考虑几种特殊情况：①A present B, B present C，参数vc为A时候的情况
/* 完整的描述请参见文件头部 */
- (UIViewController *)findCurrentShowingViewControllerFrom:(UIViewController *)vc
{
    //方法1：递归方法 Recursive method
    UIViewController *currentShowingVC;
    if ([vc presentedViewController]) { //注要优先判断vc是否有弹出其他视图，如有则当前显示的视图肯定是在那上面
        // 当前视图是被presented出来的
        UIViewController *nextRootVC = [vc presentedViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
        
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        UIViewController *nextRootVC = [(UITabBarController *)vc selectedViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
        
    } else if ([vc isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        UIViewController *nextRootVC = [(UINavigationController *)vc visibleViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
        
    } else {
        // 根视图为非导航类
        currentShowingVC = vc;
    }
    
    return currentShowingVC;
    
    /*
     //方法2：遍历方法
     while (1)
     {
     if (vc.presentedViewController) {
     vc = vc.presentedViewController;
     
     } else if ([vc isKindOfClass:[UITabBarController class]]) {
     vc = ((UITabBarController*)vc).selectedViewController;
     
     } else if ([vc isKindOfClass:[UINavigationController class]]) {
     vc = ((UINavigationController*)vc).visibleViewController;
     
     //} else if (vc.childViewControllers.count > 0) {
     //    //如果是普通控制器，找childViewControllers最后一个
     //    vc = [vc.childViewControllers lastObject];
     } else {
     break;
     }
     }
     return vc;
     //*/
}

@end
